void USART_Send8(unsigned char u8Data) {
 // Wait if a byte is being transmitted
 while (!(UCSRA & (1 << UDRE)));
 // Transmit data
 UDR = u8Data;
}

const char _THRESHOLD = 20;
char counter = 0;
char ispis = 0;
unsigned int adc_rd = 0;

sbit Chip_Select at PORTB5_bit;
sbit SoftSpi_CLK at PORTB2_bit;
sbit SoftSpi_SDI at PORTB1_bit;  // Note: Input signal
sbit SoftSpi_SDO at PORTB0_bit;
sbit Chip_Select_Direction at DDB5_bit;
sbit SoftSpi_CLK_Direction at DDB2_bit;
sbit SoftSpi_SDI_Direction at DDB1_bit;
sbit SoftSpi_SDO_Direction at DDB0_bit;


void InitMain() {
  SoftSpi_CLK_Direction  = 1;             // Set CLK pin as Output
  SoftSpi_SDI_Direction = 0;              // Set SDI pin as Input
  SoftSpi_SDO_Direction = 1;              // Set SDO pin as Output
  Chip_Select_Direction = 1;              // Set CS# pin as Output
  Soft_SPI_Init();                        // Initialize Soft_SPI
  Chip_Select = 1;                        // Disable CS
}


void Timer0Overflow_ISR() org IVT_ADDR_TIMER0_OVF {
     unsigned short data_read = Soft_SPI_Read(0xF2);

      USART_Send8(data_read);
}

void main() {
     unsigned short data_read;
     char uart_rd;
     int i = 0;
     srand(1121);
     UART1_Init(9600);               // Initialize UART module at 9600 bps
     Delay_ms(100);
     UART1_Write(0x02); // Send STX (Start of Transmission)
     UART1_Write(0x52); // Type = REQ
     UART1_Write(0x04); // Opcode = GAP_WRITE_LOCAL_NAME
     UART1_Write(0x0A); // Length = 10 (16-bit)
     UART1_Write(0x00);
     UART1_Write(0x60); // Checksum
       //DATA
     UART1_Write(0x09); // Number of characters in the name
     UART1_Write(0x4D); // ASCII -> M
     UART1_Write(0x49); // ASCII -> I
     UART1_Write(0x4E); // ASCII -> N
     UART1_Write(0x4F); // ASCII -> O
     UART1_Write(0x54); // ASCII -> T
     UART1_Write(0x41); // ASCII -> A
     UART1_Write(0x55); // ASCII -> U
     UART1_Write(0x52); // ASCII -> R
     UART1_Write(0x00); // ASCII -> NULL (ends with a NULL)
     UART1_Write(0x03); // Send ETX (End of Transmission)

     Delay_ms(100);
    //prelazak u TRANSPARENT
    UART1_Write(0x02); // Send STX (Start of Transmission)
    UART1_Write(0x52); // Type = REQ
    UART1_Write(0x4E); // Opcode = SET_EVENT_FILTER
    UART1_Write(0x01); // Length = 1 (16-bit)
    UART1_Write(0x00);
    UART1_Write(0xA1); // Checksum
    UART1_Write(0x03); // Payload = 3 (full cable replacement)
    UART1_Write(0x03); // Send ETX (End of Transmission)
    Delay_ms(100);
    InitMain();
    Delay_ms(100);
//    SREG_I_bit = 1;               // Interrupt enable
//    TOIE0_bit  = 1;               // Timer0 overflow interrupt enable
    TCCR0  = 4;                   // Start timer with 256 prescaler
   // ADC_Init();
  //  ADC_Read(0);
     while(1){
         data_read = Soft_SPI_Read(0xF5);

      USART_Send8(data_read);
      Delay_1sec();
     }
}